<template>
    <div>
        <div style="margin-bottom: 5px;">
            <el-input v-model="name" placeholder="请输入物品名" suffix-icon="el-icon-search" style="width: 200px;"
                      @keyup.enter.native="loadPost"></el-input>
            <el-select v-model="storage" placeholder="请选择仓库" style="margin-left: 5px;">
                <el-option
                        v-for="item in storageData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
            <el-select v-model="goodstype" placeholder="请选择分类" style="margin-left: 5px;">
                <el-option
                        v-for="item in goodstypeData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>

            <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button>

            <el-button type="primary" style="margin-left: 5px;" @click="add" v-if="user.roleId!=2">新增</el-button>
            <el-button type="primary" style="margin-left: 5px;" @click="inGoods" v-if="user.roleId!=2">入库</el-button>
            <el-button type="primary" style="margin-left: 5px;" @click="outGoods" v-if="user.roleId!=2">出库</el-button>
        </div>
        <el-table :data="tableData"
                  :header-cell-style="{ background: '#f2f5fc', color: '#555555' }"
                  border
                  highlight-current-row
                  @current-change="selectCurrentChange"
        >
            <el-table-column prop="id" label="ID" width="60">
            </el-table-column>
            <el-table-column prop="name" label="物品名" width="180">
            </el-table-column>
            <el-table-column prop="storage" label="仓库" width="180" :formatter="formatStorage">
            </el-table-column>
            <el-table-column prop="goodstype" label="分类" width="180" :formatter="formatGoodstype">
            </el-table-column>
            <el-table-column prop="count" label="数量" width="180">
            </el-table-column>
            <el-table-column prop="remark" label="备注">
            </el-table-column>
            <el-table-column prop="operate" label="操作" v-if="user.roleId!=2">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm
                            title="确定删除吗？"
                            @confirm="del(scope.row.id)"
                            style="margin-left: 5px;"
                    >
                        <el-button slot="reference" size="small" type="danger" >删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[5, 10, 20,30]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>

        <el-dialog
                title="物品维护"
                :visible.sync="centerDialogVisible"
                width="30%"
                center>

            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="物品名" prop="name">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="仓库" prop="storage">
                    <el-col :span="20">
                        <el-select v-model="form.storage" placeholder="请选择仓库" style="margin-left: 5px;">
                            <el-option
                                    v-for="item in storageData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>

                    </el-col>
                </el-form-item>
                <el-form-item label="分类" prop="goodstype">
                    <el-col :span="20">
                        <el-select v-model="form.goodstype" placeholder="请选择分类" style="margin-left: 5px;">
                            <el-option
                                    v-for="item in goodstypeData"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量" prop="count">
                    <el-col :span="20">
                        <el-input v-model="form.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="form.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
        </el-dialog>

        <el-dialog
                title="出入库"
                :visible.sync="inDialogVisible"
                width="30%"
                center>

            <el-dialog
                    width="75%"
                    title="用户选择"
                    :visible.sync="innerVisible"
                    append-to-body>
                <SelectUser @doSelectUser="doSelectUser"></SelectUser>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="innerVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirmUser">确 定</el-button>
                  </span>
            </el-dialog>

            <el-form ref="form1" :rules="rules1" :model="form1" label-width="80px">
                <el-form-item label="物品名">
                    <el-col :span="20">
                        <el-input v-model="form1.goodsname" readonly></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="申请人">
                    <el-col :span="20">
                        <el-input v-model="form1.username" readonly @click.native="selectUser"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="数量" prop="count">
                    <el-col :span="20">
                        <el-input v-model="form1.count"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-col :span="20">
                        <el-input type="textarea" v-model="form1.remark"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="inDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="doInGoods">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>


<script>
// 导入子组件SelectUser
import SelectUser from "../user/SelectUser";

export default {
  name: "GoodsManage", // 定义组件名称
  components: { SelectUser }, // 注册子组件，使其在模板中可用

  data() {
    // 定义数据验证函数：检查数量是否过大
    let checkCount = (rule, value, callback) => {
      if(value > 9999) {
        callback(new Error('数量输入过大'));
      } else {
        callback();
      }
    };

    // 返回组件的数据对象，定义所有响应式数据
    return {
      user: JSON.parse(sessionStorage.getItem('CurUser')), // 从会话存储中获取当前用户信息
      storageData: [], // 仓库数据数组
      goodstypeData: [], // 商品类型数据数组
      tableData: [], // 表格数据数组
      pageSize: 10, // 每页显示条数
      pageNum: 1, // 当前页码
      total: 0, // 总条数
      name: '', // 搜索物品名
      storage: '', // 搜索仓库
      goodstype: '', // 搜索商品类型
      centerDialogVisible: false, // 物品维护对话框是否可见
      inDialogVisible: false, // 出入库对话框是否可见
      innerVisible: false, // 用户选择对话框是否可见
      currentRow: {}, // 当前行数据对象
      tempUser: {}, // 临时用户数据对象
      form: { // 物品维护表单数据对象
        id: '',
        name: '',
        storage: '',
        goodstype: '',
        count: '',
        remark: ''
      },
      form1: { // 出入库表单数据对象
        goods: '',
        goodsname: '',
        count: '',
        username: '',
        userid: '',
        adminId: '',
        remark: '',
        action: '1' // 1为入库，2为出库
      },
      rules1: {}, // 出入库表单验证规则（未定义）
      rules: { // 物品维护表单验证规则
        name: [
          { required: true, message: '请输入物品名', trigger: 'blur' } // 验证物品名是否输入
        ],
        storage: [
          { required: true, message: '请选择仓库', trigger: 'blur' } // 验证仓库是否选择
        ],
        goodstype: [
          { required: true, message: '请选择分类', trigger: 'blur' } // 验证分类是否选择
        ],
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' }, // 验证数量是否输入
          { pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数字', trigger: "blur" }, // 验证数量格式
          { validator: checkCount, trigger: 'blur' } // 验证数量大小
        ],
      }
    }
  },

  methods: {
    // 选择用户后触发的方法，更新临时用户数据
    doSelectUser(val) {
      console.log(val)
      this.tempUser = val
    },
    // 确认选择用户，将临时用户数据赋值到表单1
    confirmUser() {
      this.form1.username = this.tempUser.name
      this.form1.userid = this.tempUser.id
      this.innerVisible = false
    },
    // 表格当前行变化时触发的方法，更新当前行数据
    selectCurrentChange(val) {
      this.currentRow = val;
    },
    // 格式化仓库名称，根据行数据中的仓库ID查找仓库名称
    formatStorage(row) {
      let temp = this.storageData.find(item => {
        return item.id == row.storage
      })
      return temp && temp.name
    },
    // 格式化商品类型名称，根据行数据中的类型ID查找类型名称
    formatGoodstype(row) {
      let temp = this.goodstypeData.find(item => {
        return item.id == row.goodstype
      })
      return temp && temp.name
    },
    // 重置物品维护表单
    resetForm() {
      this.$refs.form.resetFields();
    },
    // 重置出入库表单
    resetInForm() {
      this.$refs.form1.resetFields();
    },
    // 删除物品，通过GET请求发送删除指令
    del(id) {
      console.log(id)
      this.$axios.get(this.$httpUrl+'/goods/del?id='+id).then(res => res.data).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.loadPost()
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      })
    },
    // 编辑物品，将行数据赋值到物品维护表单并显示对话框
    mod(row) {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.form.id = row.id
        this.form.name = row.name
        this.form.storage = row.storage
        this.form.goodstype = row.goodstype
        this.form.count = row.count
        this.form.remark = row.remark
      })
    },
    // 新增物品，重置表单并显示对话框
    add() {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm()
        this.form.id = ''
      })
    },
    // 入库操作，设置表单1的值并显示出入库对话框
    inGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录');
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm()
        this.form1.goodsname = this.currentRow.name
        this.form1.goods = this.currentRow.id
        this.form1.adminId = this.user.id
        this.form1.action = '1'
      })
    },
    // 出库操作，设置表单1的值并显示出入库对话框
    outGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录');
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm()
        this.form1.goodsname = this.currentRow.name
        this.form1.goods = this.currentRow.id
        this.form1.adminId = this.user.id
        this.form1.action = '2'
      })
    },
    // 选择用户，显示用户选择对话框
    selectUser() {
      this.innerVisible = true
    },
    // 保存物品，通过POST请求发送保存指令
    doSave() {
      this.$axios.post(this.$httpUrl+'/goods/save', this.form).then(res => res.data).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      })
    },
    // 修改物品，通过POST请求发送修改指令
    doMod() {
      this.$axios.post(this.$httpUrl+'/goods/update', this.form).then(res => res.data).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      })
    },
    // 保存或修改物品，根据表单是否有id决定操作
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.doMod();
          } else {
            this.doSave();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 执行入库操作，通过POST请求发送入库指令
    doInGoods() {
      this.$axios.post(this.$httpUrl + '/record/save', this.form1).then(res => res.data).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          this.inDialogVisible = false
          this.loadPost()
          this.resetInForm()
        } else {
          this.$message({
            message: '操作失败！',
            type: 'error'
          });
        }
      })
    },
    // 处理分页大小变化事件，更新分页参数并重新加载数据
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageNum=1
                this.pageSize=val
                this.loadPost()
            },
    //处理当前页变化事件，更新页码并重新加载数据
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum=val
                this.loadPost()
            },
    // 重置搜索参数
            resetParam(){
                this.name=''
                this.storage=''
                this.goodstype=''
            },
    // 加载物品数据，根据分页参数和搜索参数发送POST请求
            loadPost(){
                this.$axios.post(this.$httpUrl+'/goods/listPage',{
                    pageSize:this.pageSize,
                    pageNum:this.pageNum,
                    param:{
                        name:this.name,
                        goodstype:this.goodstype+'',
                        storage:this.storage+''
                    }
                }).then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.tableData=res.data
                        this.total=res.total
                    }else{
                        alert('获取数据失败')
                    }

                })
            },
    // 加载仓库数据，发送GET请求获取仓库列表
            loadStorage(){
                this.$axios.get(this.$httpUrl+'/storage/list').then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.storageData=res.data
                    }else{
                        alert('获取数据失败')
                    }

                })
            },
    // 加载商品类型数据，发送GET请求获取商品类型列表
            loadGoodstype(){
                this.$axios.get(this.$httpUrl+'/goodstype/list').then(res=>res.data).then(res=>{
                    console.log(res)
                    if(res.code==200){
                        this.goodstypeData=res.data
                    }else{
                        alert('获取数据失败')
                    }

                })
            }
        },
  // 在组件挂载前执行的方法，用于初始化数据
        beforeMount() {
            this.loadStorage()
            this.loadGoodstype()
            this.loadPost()

        }
    }
</script>

<style scoped>

</style>